package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.controller.vo.ShowInfoVo;
import com.hunttown.mes.rpc.domain.*;
import com.hunttown.mes.rpc.domain.enums.enterprise.EnterpriseTypeEnum;
import com.hunttown.mes.rpc.domain.enums.user.UserLevelEnum;
import com.hunttown.mes.rpc.domain.enums.user.UserTypeEnum;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import com.hunttown.mes.rpc.domain.query.TransportNewsDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportUserDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 会员
 * @author: wangjunfu
 * @date: 2019-07-06 14:44:48
 * @description: 按正常的理解应该是“真实姓名”可以重复，“呢称”不可以重复。
 * 当前系统中，相反（由于历史数据原因）。不过不影响系统运行。
 */
@Controller
@RequestMapping(value = "/basic/user")
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    private final AnalysisManageManageService manageService;
    private final AnalysisCatalogManageService catalogService;
    private final TransportUserManageService userService;
    private final TransportUserCardManageService userCardService;
    private final TransportOperateLogManageService logService;
    private final TransportNewsManageService newsService;
    private final IotRegionManageService iotRegionService;
    private final ModelService modelService;

    @Autowired
    public UserController(TransportUserManageService userService, AnalysisManageManageService manageService, AnalysisCatalogManageService catalogService, ModelService modelService, TransportUserCardManageService userCardService, TransportOperateLogManageService logService, TransportNewsManageService newsService, IotRegionManageService iotRegionService) {
        this.userService = userService;
        this.manageService = manageService;
        this.catalogService = catalogService;
        this.modelService = modelService;
        this.userCardService = userCardService;
        this.logService = logService;
        this.newsService = newsService;
        this.iotRegionService = iotRegionService;
    }

    //region 数据列表

    /**
     * 首页
     * index ------------ 通用
     * index-transport -- 客运
     * index-meter ------ 电表
     * index-person ----- 个人
     * index-enterprise - 企业
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = {"/index", "/index-transport", "/index-meter", "/index-person", "/index-enterprise"}, method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, TransportUserDTOQuery dtoQuery) {

        String uri = request.getRequestURI();

        //region 显示标题（这里其实没必要设置，为了作标记，怕时间长了忘了）
        String showTitle = "用户信息";

        if (uri.toLowerCase().contains("/index-transport")) {
            showTitle = "客户信息";
        }
        if (uri.toLowerCase().contains("/index-meter")) {
            showTitle = "租户信息";
        }
        if (uri.toLowerCase().contains("/index-person")) {
            showTitle = "个人用户";
            dtoQuery.setNotRegisterType(2); //非企业用户
        }
        if (uri.toLowerCase().contains("/index-enterprise")) {
            showTitle = "企业用户";
            dtoQuery.setRegisterType(2);
        }
        model.addAttribute("showTitle", showTitle);
        //endregion

        //停用、离职
        if (dtoQuery.getOffJob() == null) {
            dtoQuery.setOffJob(0);
        }

        //默认不显示停用
        dtoQuery.setStopFlag(0);

        if (dtoQuery.getOffJob() == 1) {
            dtoQuery.setStopFlag(null);
        }

        dtoQuery.setOrderBy("order by id desc");
        Page<TransportUserDTO> dataPage = userService.getForPage(dtoQuery);

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (TransportUserDTO item : dataPage.getItems()) {
                //item.setCompanyName(modelService.getCompanyName(item.getCompanyId()));
                item.setUserLevelName(UserLevelEnum.getEnumByKey(item.getUserLevel()));
                item.setUserTypeName(UserTypeEnum.getEnumByKey(item.getUserType()));

                //会员卡
                TransportUserCardDTO userCardDTO = userCardService.getByUserId(item.getId());
                if (userCardDTO != null) {
                    item.setCardNo(userCardDTO.getCardNo());
                    item.setCardValue(userCardDTO.getCardValue());
                } else {
                    item.setCardNo("--");
                    item.setCardValue(new BigDecimal(0));
                }

                //区域
                item.setIotRegionName(modelService.getIotRegionName(item.getIotRegionId()));
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        model.addAttribute("userLevelList", UserLevelEnum.getEnumList());

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);

        //编辑、删除
        String[] menus = {"Y-Y-YHXX-BJ", "Y-Y-YHXX-SC", "Y-Y-YHXX-QTY",
                "Y-Y-KHXX-BJ", "Y-Y-KHXX-SC", "Y-Y-KHXX-QTY",
                "Y-Y-ZHXX-BJ", "Y-Y-ZHXX-SC", "Y-Y-ZHXX-QTY",
                "H-H-GRYH-BJ", "H-H-GRYH-SC", "H-H-GRYH-QTY",
                "H-H-QYYH-BJ", "H-H-QYYH-SC", "H-H-QYYH-QTY",
                "Y-Y-HYK-LB"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return uri;
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return vm
     */
    @RequestMapping(value = {"/edit", "/edit-person", "/edit-enterprise"}, method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer id) {
        id = (id == null ? 0 : id);

        String uri = request.getRequestURI();

        TransportUserDTO obj;

        if (id > 0) {
            obj = userService.getById(id);

            if (obj.getRegisterType() == null || obj.getRegisterType() == 0) {
                obj.setRegisterType(1);
            }

            //region 省市地址
            if (obj.getProvince() > 0) {
                modelService.getRegionPage(model, obj.getProvince(), "cityPage");
            }
            if (obj.getCity() > 0) {
                modelService.getRegionPage(model, obj.getCity(), "countyPage");
            }
            //endregion

        } else {
            obj = new TransportUserDTO();
            obj.setId(id);
            obj.setSex(1);
            obj.setMarry(2);
            obj.setBirthday("1900-01-01");
            obj.setAge(0);
            obj.setCardType(1);
            obj.setUserLevel(1);
            obj.setIsCanRecharge(1);
            obj.setLimitRecharge(BigDecimal.ZERO);
            obj.setIsCertification(0);
            obj.setExamineStatus(0);
            obj.setMemberNumber(0);
            obj.setBranchId(0);

            if (uri.toLowerCase().contains("/edit-enterprise")) {
                obj.setRegisterType(2);
            } else {
                obj.setRegisterType(1);
            }
        }

        if (StringUtils.isBlank(obj.getHeadPic())) {
            obj.setHeadPic("/static/assets/images/noimage-1.png");
        }

        if (StringUtils.isBlank(obj.getCardPicFront())) {
            obj.setCardPicFront("/static/assets/images/noimage-2.png");
        }

        if (StringUtils.isBlank(obj.getCardPicBack())) {
            obj.setCardPicBack("/static/assets/images/noimage-2.png");
        }

        if (StringUtils.isBlank(obj.getCertificateNo()) && obj.getId() > 0 && obj.getRegisterType() > 0) {
            obj.setCertificateNo((obj.getRegisterType() == 1 ? "P" : "E") + StringUtils.padLeft(obj.getId(), 8));
        }

        model.addAttribute("Obj", obj);

        modelService.getCompayPage(model, 1, 0, null);
        modelService.getIotRegionPage(model);
        model.addAttribute("userLevelList", UserLevelEnum.getEnumList());

        //区域信息
        modelService.getRegionPage(model, 0, "provincePage");

        //企业性质
        model.addAttribute("enterpriseTypList", EnterpriseTypeEnum.getEnumList());

        //region 推荐机构（文章列表获取：jigoushezhi）
        AnalysisVisualCatalogDTO catalog = catalogService.getByCateEnName("jigoushezhi");
        if (catalog != null) {
            TransportNewsDTOQuery newQuery = new TransportNewsDTOQuery();
            newQuery.setCatalogId(catalog.getId());
            newQuery.setStopFlag(0);
            newQuery.setPageSize(1000);
            Page<TransportNewsDTO> jigouPage = newsService.getForPage(newQuery);
            model.addAttribute("jigouPage", jigouPage);
        }
        //endregion

        return uri;
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportUserDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            objDTO.setLogonName(objDTO.getLogonName().trim());  //检查空格
            objDTO.setMobile(objDTO.getMobile().trim());        //检查空格
            objDTO.setTrueName(objDTO.getTrueName().trim());    //检查空格
            objDTO.setTrueName(objDTO.getTrueName().replace("(", "（").replace(")", "）"));

            System.out.println("转拼音的结果：" + ChineseToPinyinUtils.ToPinyin(objDTO.getTrueName()));
            System.out.println("过滤后的结果：" + EmojiFilterUtils.filterUnqualifiedLetter(objDTO.getTrueName()));

            if (objDTO.getTrueName().length() < 2 || !Html2TextUtils.judgeUsername(objDTO.getTrueName())) {
                map = OperateCode.CompositionResult(map, -10, "会员姓名不合理！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            if (!RegexpUtils.checkIsMobile(objDTO.getMobile())) {
                map = OperateCode.CompositionResult(map, -10, "请输入正确的手机号！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            // 生成密码
            if (StringUtils.isNotBlank(objDTO.getLogonPwdFront())) {
                objDTO.setLogonPwd(LogonUtils.getKeyGen(objDTO.getLogonName(), objDTO.getLogonPwdFront().trim()));
            }

            if (objDTO.getIsCanRecharge() == null) {
                objDTO.setIsCanRecharge(0);
            }

            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }

            if (objDTO.getCompanyId() > 0) {    //企业会员
                objDTO.setUserType(2);
            } else {
                objDTO.setUserType(1);
            }

            if (objDTO.getProvince() == null) {
                objDTO.setProvince(0);
            }
            if (objDTO.getCity() == null) {
                objDTO.setCity(0);
            }
            if (objDTO.getArea() == null) {
                objDTO.setArea(0);
            }
            if (objDTO.getTown() == null) {
                objDTO.setTown(0);
            }
            if (objDTO.getVillage() == null) {
                objDTO.setVillage(0);
            }

            //region 检查数据库是否存在当前用户

            // 新增时检验帐号：新增后帐号不允许修改
            if ((objDTO.getId() == null || objDTO.getId() <= 0) && StringUtils.isNotBlank(objDTO.getLogonName())) {
                TransportUserDTOQuery logon_query = new TransportUserDTOQuery();
                logon_query.setLogonName(objDTO.getLogonName().trim()); //即使是删除和停用的也不可以。
                TransportUserDTO logon_obj = userService.getByQuery(logon_query);
                if (logon_obj != null && logon_obj.getId() > 0) {
                    map = OperateCode.CompositionResult(map, -10, "此帐号已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            // 新增修改时检查手机号：检验手机号是否重复
            // 双中横线不判断
            if (!objDTO.getMobile().equals("--")) {
                TransportUserDTOQuery mobile_query = new TransportUserDTOQuery();
                mobile_query.setMobile(objDTO.getMobile()); //即使是删除和停用的也不可以。
                TransportUserDTO mobile_obj = userService.getByQuery(mobile_query);
                if (mobile_obj != null && !Objects.equals(mobile_obj.getId(), objDTO.getId())) {
                    map = OperateCode.CompositionResult(map, -10, "此手机号已经存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            // 新增修改时检验真实姓名：真实姓名是否重复
            TransportUserDTOQuery name_query = new TransportUserDTOQuery();
            name_query.setTrueName(objDTO.getTrueName()); //即使是删除和停用的也不可以。
            TransportUserDTO name_obj = userService.getByQuery(name_query);
            if (name_obj != null && !Objects.equals(name_obj.getId(), objDTO.getId())) {
                map = OperateCode.CompositionResult(map, -10, "此用户姓名已经存在，请重新输入！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            //endregion

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                // 新增
                // 赋初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setUpdateTime(new Date());
                objDTO.setRegTime(new Date());
                objDTO.setRegIp(IpUtils.getClientIp(request));
                objDTO.setLastLoginTime(new Date());
                objDTO.setLastLoginIp(IpUtils.getClientIp(request));
                objDTO.setLoginTimes(0);
                objDTO.setDeleteFlag(0);

                objDTO.setNickName(Html2TextUtils.filterBrackets(objDTO.getTrueName()));   //呢称默认为真实姓名，并去格式
                objDTO.setLogonName(objDTO.getMobile());    //登录帐号默认为手机号

                objDTO.setRelId(0);
                objDTO.setManageId(0);
                objDTO.setDriverId(0);
                objDTO.setStaffId(0);
                objDTO.setIsAuth(0);
                objDTO.setCountry("");
                objDTO.setZipCode("");
                objDTO.setFax("");
                objDTO.setQq("");
                objDTO.setAliww("");
                objDTO.setWeibo("");
                objDTO.setWeixin("");
                objDTO.setMsn("");
                objDTO.setHomePage("");
                objDTO.setPersonSign("");
                objDTO.setPhotoUrl("");
                objDTO.setPersonDes("");
                objDTO.setIsBindWxapp(0);

                //健康项目时新增
                //objDTO.setRegisterType(0);
                //objDTO.setIsCertification(0);
                //objDTO.setExamineStatus(0);

                objDTO.setEnterpriseType(0);
                objDTO.setRegisterCapital(0);
                objDTO.setFoundDate(DateConvertUtils.strToDate("1990-01-01"));

                //浙商城特殊需求
                objDTO.setIsCanRecharge(1);
                objDTO.setLimitRecharge(BigDecimal.ZERO);

                // 初始化时如果没有设置空码，则给一个默认值
                if (StringUtils.isBlank(objDTO.getLogonPwdFront())) {
                    objDTO.setLogonPwd("3DBF15878A732084");  //我也不知道是什么密码，但肯定登录不了！
                }

                objDTO = userService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                //保存成功同时生成一条会员卡记录（默认充值卡）
                userCardService.insertSimple(objDTO.getId(), 0);

            } else {
                // 修改
                boolean isEditMobile = false; //是否修改了手机号
                TransportUserDTO olduser = userService.getFromCacheId(objDTO.getId());
                if (!olduser.getMobile().equals(objDTO.getMobile())) {
                    isEditMobile = true;
                }

                // 剔除不需要修改的字段
                objDTO.setLogonName(null);
                objDTO.setNickName(null);

                // 编辑时如果没有设置空码，则设为null
                if (StringUtils.isBlank(objDTO.getLogonPwdFront())) {
                    objDTO.setLogonPwd(null);
                }

                Boolean isNext = userService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                //1.修改了用户，同时要更新设备表的区域ID

                //2.如果修改了手机号，那么要同步更新管理员、司机、员工档案中的手机号
                if (isEditMobile) {
                    //更新管理员手机号
                    if (olduser.getManageId() > 0) {
                        AnalysisManageDTO update = new AnalysisManageDTO();
                        update.setId(olduser.getManageId());
                        update.setMobile(objDTO.getMobile());
                        manageService.updateInfoById(update);
                    }
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 78, objDTO.getId(), 2,
                    "更新会员信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            e.printStackTrace();

            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = userService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 78, id, 4,
                    "删除会员信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = userService.changeState(id, status, -1);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 78, id == null ? 0 : id, 2,
                    "更新会员状态",
                    "记录状态更新" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return json
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        TransportUserDTO obj = new TransportUserDTO();
        obj.setId(id);

        if (id > 0) {
            obj = userService.getById(id);
        }
        userService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //详情
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    public String getInfo(Model model, Integer id) {

        //显示标题
        String showTitle = "未知";

        //数据
        ShowInfoVo vo;
        List<ShowInfoVo> dataList = new ArrayList<>();

        if (id != null && id > 0) {
            TransportUserDTO obj = userService.getById(id);

            if (obj != null) {
                vo = new ShowInfoVo();
                vo.setKey("编号ID");
                vo.setValue(obj.getId());
                dataList.add(vo);

                //企业信息
                if (obj.getRegisterType() == 2) {
                    showTitle = obj.getEnterpriseName();

                    vo = new ShowInfoVo();
                    vo.setKey("企业名称");
                    vo.setValue(obj.getEnterpriseName());
                    dataList.add(vo);

                    vo = new ShowInfoVo();
                    vo.setKey("统一社会信用代码");
                    vo.setValue(obj.getSocialCreditCode());
                    dataList.add(vo);

                    vo = new ShowInfoVo();
                    vo.setKey("企业法人");
                    vo.setValue(obj.getEnterpriseLegalPerson());
                    dataList.add(vo);

                    vo = new ShowInfoVo();
                    vo.setKey("企业电话");
                    vo.setValue(obj.getEnterpriseTel());
                    dataList.add(vo);

                    vo = new ShowInfoVo();
                    vo.setKey("营业执照");
                    vo.setValue("<img src=\"" + obj.getCardPicFront() + "\" width=\"160px\" height=\"90px\" alt=\"营业执照\">");
                    dataList.add(vo);

                    if (obj.getProvince() != null && obj.getProvince() > 0) {
                        vo = new ShowInfoVo();
                        vo.setKey("企业地址");
                        vo.setValue(modelService.getRegionName(obj.getProvince()) + "," + modelService.getRegionName(obj.getCity()) + "," + modelService.getRegionName(obj.getArea()));
                        dataList.add(vo);

                        vo = new ShowInfoVo();
                        vo.setKey("详细地址");
                        vo.setValue(obj.getDetailAddress());
                        dataList.add(vo);
                    }
                } else {
                    showTitle = obj.getTrueName();
                }

                vo = new ShowInfoVo();
                vo.setKey("头像");
                vo.setValue("<img src=\"" + obj.getHeadPic() + "\" width=\"75px\" height=\"75px\" alt=\"头像\">");
                dataList.add(vo);

                if (obj.getRegisterType() == 2) {
                    vo = new ShowInfoVo();
                    vo.setKey("联系人");
                    vo.setValue(obj.getTrueName());
                    dataList.add(vo);
                } else {
                    vo = new ShowInfoVo();
                    vo.setKey("真实姓名");
                    vo.setValue(obj.getTrueName());
                    dataList.add(vo);

                    vo = new ShowInfoVo();
                    vo.setKey("会员性别");
                    vo.setValue(obj.getSex() == 1 ? "女" : (obj.getSex() == 0 ? "男" : "未知"));
                    dataList.add(vo);

                    vo = new ShowInfoVo();
                    vo.setKey("婚姻状况");
                    vo.setValue(obj.getMarry() == 1 ? "已婚" : (obj.getMarry() == 0 ? "未婚" : "保密"));
                    dataList.add(vo);

                }

                vo = new ShowInfoVo();
                vo.setKey("手机号码");
                vo.setValue(obj.getMobile());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("联系邮箱");
                vo.setValue(obj.getEmail());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("用户级别");
                vo.setValue(UserLevelEnum.getEnumByKey(obj.getUserLevel()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("证书编号");
                vo.setValue(obj.getCertificateNo());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("会员类型");
                vo.setValue(obj.getRegisterType() == 2 ? "企业" : "个人");
                dataList.add(vo);

                if (obj.getRegisterType() != 2) {
                    if (obj.getProvince() != null && obj.getProvince() > 0) {
                        vo = new ShowInfoVo();
                        vo.setKey("企业地址");
                        vo.setValue(modelService.getRegionName(obj.getProvince()) + "," + modelService.getRegionName(obj.getCity()) + "," + modelService.getRegionName(obj.getArea()));
                        dataList.add(vo);

                        vo = new ShowInfoVo();
                        vo.setKey("详细地址");
                        vo.setValue(obj.getDetailAddress());
                        dataList.add(vo);
                    }

                    if (StringUtils.intIsNotBlank(obj.getIotRegionId())) {
                        vo = new ShowInfoVo();
                        vo.setKey("户号");
                        vo.setValue(modelService.getIotRegionName(obj.getIotRegionId()) + "，" + obj.getDetailAddress());
                        dataList.add(vo);
                    }
                }

                if (obj.getRegisterType() != 2) {
                    vo = new ShowInfoVo();
                    vo.setKey("身份证号");
                    vo.setValue(obj.getCardNumber());
                    dataList.add(vo);

                    vo = new ShowInfoVo();
                    vo.setKey("身份证正");
                    vo.setValue("<img src=\"" + obj.getCardPicFront() + "\" width=\"160px\" height=\"90px\" alt=\"身份证正\">");
                    dataList.add(vo);

                    vo = new ShowInfoVo();
                    vo.setKey("身份证反");
                    vo.setValue("<img src=\"" + obj.getCardPicBack() + "\" width=\"160px\" height=\"90px\" alt=\"身份证反\">");
                    dataList.add(vo);
                }

                vo = new ShowInfoVo();
                vo.setKey("实名认证");
                vo.setValue(obj.getIsCertification() == 1 ? "已认证" : "未认证 ");
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("审核状态");
                vo.setValue(obj.getExamineStatus() == 1 ? "已审核" : "未审核 ");
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("自行充值");
                vo.setValue(obj.getIsCanRecharge() == 1 ? "可以" : "不可以 ");
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("限制金额");
                vo.setValue(obj.getLimitRecharge().compareTo(BigDecimal.ZERO) == 0 ? "不限" : obj.getLimitRecharge());
                dataList.add(vo);

                if (StringUtils.isNotBlank(obj.getStarSigns())) {
                    vo = new ShowInfoVo();
                    vo.setKey("星座");
                    vo.setValue(obj.getStarSigns());
                    dataList.add(vo);
                }

                if (StringUtils.isNotBlank(obj.getBloodtype())) {
                    vo = new ShowInfoVo();
                    vo.setKey("血型");
                    vo.setValue(obj.getBloodtype());
                    dataList.add(vo);
                }

                if (StringUtils.isNotBlank(obj.getBodySize())) {
                    vo = new ShowInfoVo();
                    vo.setKey("体型");
                    vo.setValue(obj.getBodySize());
                    dataList.add(vo);
                }

                if (StringUtils.isNotBlank(obj.getEducation())) {
                    vo = new ShowInfoVo();
                    vo.setKey("学历");
                    vo.setValue(obj.getEducation());
                    dataList.add(vo);
                }

                if (StringUtils.isNotBlank(obj.getProfession())) {
                    vo = new ShowInfoVo();
                    vo.setKey("职业");
                    vo.setValue(obj.getProfession());
                    dataList.add(vo);
                }

                vo = new ShowInfoVo();
                vo.setKey("帐号状态");
                vo.setValue(obj.getStopFlag() == 0 ? "正常" : "停用");
                dataList.add(vo);

                if (obj.getRegisterType() == 2) {
                    vo = new ShowInfoVo();
                    vo.setKey("企业简介");
                    vo.setValue(obj.getPersonDes());
                    dataList.add(vo);
                } else {
                    vo = new ShowInfoVo();
                    vo.setKey("个人简介");
                    vo.setValue(obj.getPersonDes());
                    dataList.add(vo);
                }
            }

            model.addAttribute("showTitle", showTitle);
            model.addAttribute("dataList", dataList);
        }

        return "show/getinfo-template";
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(Model model, Integer id) {
        if (id == null || id <= 0) {
            throw new RuntimeException("未查询到数据！");
        }

        TransportUserDTO obj = userService.getById(id);
        if (obj == null) {
            throw new RuntimeException("未查询到数据！");
        }

        obj.setEnterpriseTypeName(EnterpriseTypeEnum.getEnumByKey(obj.getEnterpriseType()));
        obj.setProvinceName(modelService.getRegionName(obj.getProvince()));
        obj.setCityName(modelService.getRegionName(obj.getCity()));
        obj.setAreaName(modelService.getRegionName(obj.getArea()));

        if (obj.getBranchId() > 0) {
            TransportNewsDTO newsDTO = newsService.getById(obj.getBranchId());
            if (newsDTO != null) {
                obj.setBranchName(newsDTO.getFullTitle());
            }
        }

        if (StringUtils.isBlank(obj.getHeadPic())) {
            obj.setHeadPic("/static/assets/images/noimage-1.png");
        }

        if (StringUtils.isBlank(obj.getCardPicFront())) {
            obj.setCardPicFront("/static/assets/images/noimage-2.png");
        }

        if (StringUtils.isBlank(obj.getCardPicBack())) {
            obj.setCardPicBack("/static/assets/images/noimage-2.png");
        }

        model.addAttribute("Obj", obj);

        //个人会员
        String vm = "detail-person";

        //企业会员
        if (obj.getRegisterType() == 2) {
            vm = "detail-enterprise";
        }

        return "basic/user/" + vm;
    }
    //endregion

    //region 根据手机号获取用户信息

    /**
     * 根据手机号获取用户信息
     *
     * @param mobile 手机
     * @return map
     */
    @RequestMapping(value = "/getUserByMobile", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> getUserByMobile(String mobile) {
        Map<Object, Object> map = new HashMap<>();
        map.put("userid", "");
        map.put("username", "");

        if (StringUtils.isNotBlank(mobile)) {
            TransportUserDTO dto = userService.getByMobile(mobile);
            if (dto != null) {
                map.put("userid", dto.getId());
                map.put("username", dto.getTrueName());
            }
        }

        return map;
    }
    //endregion

    //region 检查用户是否存在，不存在则添加

    // 根据 truename 获取对象
    @RequestMapping(value = "/getByTruename", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getByTruename(String truename) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("truename", "none");
        map.put("id", "0");

        try {

            if (StringUtils.isNotBlank(truename)) {
                TransportUserDTO dto = userService.getByTrueName(truename);
                if (dto != null) {
                    map.put("id", dto.getId().toString());
                    map.put("truename", URLEncoder.encode(dto.getTrueName(), "UTF-8"));
                    map.put("mobile", dto.getMobile());
                    map.put("sex", dto.getSex());
                    map.put("cardNumber", dto.getCardNumber());
                }
            }
        } catch (Exception ex) {
            //todo
        }

        return map;
    }

    /**
     * 把用户添加到数据库
     *
     * @param request  request
     * @param truename 姓名
     * @param mobile   手机号
     * @param userId   0新增 大于0更新
     * @return amp
     */
    @RequestMapping(value = "/addUserToDb", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addUserToDb(HttpServletRequest request, String truename, String mobile, Integer userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", "0");
        map.put("truename", "none");
        map.put("returnCode", 0);

        try {

            if (StringUtils.isNotBlank(truename) && StringUtils.isNotBlank(mobile)) {

                mobile = mobile.trim();        //检查空格
                truename = truename.trim();    //检查空格
                truename = truename.replace("(", "（").replace(")", "）");

                //姓名至少两个字
                if (truename.length() < 2 || !Html2TextUtils.judgeUsername(truename)) {
                    map.put("returnMessage", "提示：会员姓名不合理，请重新输入！");
                    return map;
                }

                //是否是手机号
                if (!RegexpUtils.checkIsMobile(mobile)) {
                    map.put("returnMessage", "提示：请输入正确的手机号！");
                    return map;
                }

                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

                if (userId > 0) {
                    TransportUserDTO update = new TransportUserDTO();
                    update.setId(userId);
                    update.setTrueName(truename);
                    update.setMobile(mobile);
                    update.setStopFlag(0);
                    update.setDeleteFlag(0);
                    Boolean isNext = userService.updateInfoById(update);
                    if (isNext) {
                        map.put("id", userId);
                        map.put("truename", URLEncoder.encode(truename, "UTF-8"));
                        map.put("mobile", mobile);
                        map.put("returnCode", 1);
                    } else {
                        map.put("returnMessage", "提示：会员信息更新失败，请到会员中心操作！");
                    }

                    //region *** 更新信息完毕记录操作日志 ***
                    logService.insertSimple(1, 78, userId, 2,
                            "检查用户并自动更新",
                            "TRUENMAE：" + truename + "；MOBILE：" + mobile + "；USERID:" + userId,
                            curr_obj.getId(),
                            IpUtils.getClientIp(request),
                            SystemUtils.getBrowserInfo(request));
                    //endregion

                    return map;
                }

                //检查真实姓名是否存在
                TransportUserDTOQuery truename_query = new TransportUserDTOQuery();
                truename_query.setTrueName(truename.trim());   //即使是停用的也不可以。
                TransportUserDTO truename_obj = userService.getByQuery(truename_query);
                if (truename_obj != null && truename_obj.getId() > 0) {
                    map.put("id", truename_obj.getId());
                    map.put("truename", truename_obj.getTrueName());
                    map.put("mobile", truename_obj.getMobile());
                    map.put("returnCode", -1);
                    map.put("returnMessage", "提示：此用户（" + truename_obj.getTrueName() + " - " + truename_obj.getMobile() + "）已存在，请到会员中心更新！");
                    return map;
                }

                //检查手机号是否存在
                TransportUserDTOQuery mobile_query = new TransportUserDTOQuery();
                mobile_query.setMobile(mobile.trim()); //即使是停用的也不可以。
                TransportUserDTO mobile_obj = userService.getByQuery(mobile_query);
                if (mobile_obj != null && mobile_obj.getId() > 0) {
                    map.put("id", mobile_obj.getId());
                    map.put("truename", mobile_obj.getTrueName());
                    map.put("mobile", mobile_obj.getMobile());
                    map.put("returnCode", -1);
                    map.put("returnMessage", "提示：此手机号（" + mobile_obj.getTrueName() + " - " + mobile_obj.getMobile() + "）已存在，请到会员中心更新！");
                    return map;
                }

                Integer id = userService.insertSimple(truename, mobile, curr_obj.getId());
                if (id > 0) {
                    map.put("id", id.toString());
                    map.put("truename", URLEncoder.encode(truename, "UTF-8"));
                    map.put("mobile", mobile);
                    map.put("returnCode", 1);
                } else {
                    map.put("returnMessage", URLEncoder.encode("错误信息：系统出错了！", "UTF-8"));
                }

                //region *** 更新信息完毕记录操作日志 ***
                logService.insertSimple(1, 78, id, 2,
                        "检查用户并自动添加",
                        "TRUENMAE：" + truename + "；MOBILE：" + mobile + "；USERID:" + userId,
                        curr_obj.getId(),
                        IpUtils.getClientIp(request),
                        SystemUtils.getBrowserInfo(request));
                //endregion

            } else {
                map.put("returnMessage", URLEncoder.encode("提示：姓名或手机号不能为空", "UTF-8"));
            }

        } catch (Exception ex) {
            map.put("returnMessage", ex.getMessage());
        }

        return map;
    }

    //endregion

    //region 根据用户名获取（管理员、司机等会员）

    /**
     * 根据用户名获取（管理员、司机等会员）
     *
     * @param userName 姓名..模糊
     * @param mobile   手机号..模糊
     * @return 列表
     */
    @RequestMapping(value = "/getManageDriverUser", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> getManageDriverUser(String userName, String mobile, Integer pn, Integer pageSize) {
        pn = (pn == null || pn <= 0) ? 1 : pn;
        pageSize = (pageSize == null || pageSize <= 0) ? 5 : pageSize;

        Map<Object, Object> map = new HashMap<>();
        map.put("username", userName);
        map.put("mobile", mobile);
        map.put("pn", pn);
        map.put("pageSize", pageSize);

        TransportUserDTOQuery userQuery = new TransportUserDTOQuery();
        if (StringUtils.isNotBlank(userName)) {
            userQuery.setLikeName(userName);
        }
        if (StringUtils.isNotBlank(mobile)) {
            userQuery.setMobileLike(mobile);
        }
        userQuery.setManageOrDriver(1);
        userQuery.setStopFlag(0);
        userQuery.setPn(pn);
        userQuery.setPageSize(pageSize);
        Page<TransportUserDTO> dataPage = userService.getForPage(userQuery);

        map.put("userAjaxPage", dataPage);
        map.put("userAjaxPagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        return map;
    }
    //endregion

    //region 审核和实名认证

    //审核会员
    @RequestMapping(value = "/saveExamine", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveExamine(HttpServletRequest request, Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);
        map.put("returnMessage", "审核失败！");

        if (id > 0) {
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            TransportUserDTO obj = userService.getFromCacheId(id);
            if (obj == null) {
                return map;
            }

            TransportUserDTO update = new TransportUserDTO();
            update.setId(id);
            update.setExamineStatus(1);

            if (StringUtils.isBlank(obj.getCertificateNo()) && obj.getRegisterType() > 0) {
                update.setCertificateNo((obj.getRegisterType() == 1 ? "P" : "E") + StringUtils.padLeft(obj.getId(), 8));
            }

            boolean isNext = userService.updateInfoById(update);

            if (isNext) {
                map.put("returnCode", 1);
                map.put("returnMessage", "审核成功！");
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 78, id, 2,
                    "会员审核",
                    "会员审核：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion
        }

        return map;
    }

    //审核会员实名认证
    @RequestMapping(value = "/saveCertification", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveCertification(HttpServletRequest request, Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);
        map.put("returnMessage", "审核失败！");

        if (id > 0) {
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            TransportUserDTO obj = userService.getFromCacheId(id);
            if (obj == null) {
                return map;
            }

            TransportUserDTO update = new TransportUserDTO();
            update.setId(id);
            update.setIsCertification(1);

            if (StringUtils.isBlank(obj.getCertificateNo()) && obj.getRegisterType() > 0) {
                update.setCertificateNo((obj.getRegisterType() == 1 ? "P" : "E") + StringUtils.padLeft(obj.getId(), 8));
            }

            boolean isNext = userService.updateInfoById(update);

            if (isNext) {
                map.put("returnCode", 1);
                map.put("returnMessage", "审核成功！");
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 78, id, 2,
                    "审核会员实名认证",
                    "实名认证：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion
        }

        return map;
    }
    //endregion
}